<template>
  <div class="view-container">
    <div class="app-title-container title-position">
      <modules-title
        title-name="立项决议审批详情"
        style="margin-bottom: 20px;"
      >
        <template
          v-if="detailData"
          slot="btn"
        >
          <el-button
            plain
            @click="goBack"
          >返回</el-button>
          <!-- <el-button
            v-hasPermi="{v:['project:my:audit'], isF: detailData.info_status==3&&isAudit}"
            type="primary"
            @click="handleAudit"
          >
            {{ auditButtonName }}</el-button> -->

          <approval
            :affair.sync="auditData"
            :is-text="false"
            @refresh="refreshData"
            @submit="onSubmit"
            @toEdit="toEdit"
            @cancel="onCancel"
          >
            <template slot="next">
              <el-form
                ref="auditForm"
                :model="auditForm"
                :rules="rules"
                label-width="120px"
              >
                <el-form-item
                  label="立项决议结论"
                  prop="check_status"
                >
                  <el-select
                    v-model="auditForm.check_status"
                    placeholder="请选择立项决议结论"
                    :style="{ width: '100%' }"
                  >
                    <el-option
                      v-for="(item, index) in auditOptions"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
            </template>
          </approval>

        </template>
      </modules-title>
    </div>
    <div
      v-if="detailData"
      class="main-content-container"
    >
      <el-tabs v-model="activeName1">
        <el-tab-pane name="1">
          <div slot="label"><i
              class="el-icon-tickets"
              style="margin-right:5px"
            /><span>基本信息</span></div>
          <div class="baseInfo-container">
            <baseInfo
              :detail-data="detailData"
              :title-show="false"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane
          v-if="detailData.info_status>=1"
          name="2"
        >
          <div slot="label"><i
              class="el-icon-document-copy"
              style="margin-right:5px"
            /><span>调研报告</span></div>
          <div class="tab-content">
            <!-- <div class="tip-container">
              <p class="tip-title">参与调研部门：</p>
              <p class="department-container">
                <el-tag v-for="(dep,depidx) in departmentList" :key="depidx" :type="dep.if_commit==1?'success':'danger'" size="medium" effect="plain" class="dep-tag" @click="depTagClick(dep)">
                  <span>{{ dep.department_name }}</span>
                  <el-tooltip :content="dep.if_commit==1?'已提交调研报告':'未提交调研报告'" placement="bottom" effect="light">
                    <i :class="['icon', dep.if_commit==1?'el-icon-circle-check':'el-icon-warning-outline']" />
                  </el-tooltip>
                </el-tag>
              </p>
            </div> -->
            <all-look-info
              from="audit"
              :all-look-info-list="departmentList"
            />
            <!-- <look-info
              v-else
              :department-data="departmentData"
              :project-id="detailData.id"
              :department-look-info="departmentLookInfo"
              :list-data="detailData.department_research"
              from="audit"
              @lookInfoSuccess="lookInfoSuccess"
            /> -->
          </div>
        </el-tab-pane>
      </el-tabs>
      <div
        class="tab-container"
        style="margin-top:20px;"
      >
        <meeting-list :project-id="projectId" />
      </div>
      <div
        class="tab-container"
        style="margin-top:20px;"
      >
        <div class="tab-content">
          <comment-view
            :datas="auditData"
            is-show
          />
        </div>
      </div>
    </div>

    <!-- 决议审批 -->
    <!-- <audit-dialog ref="auditDialog" :project-id="projectId" :audit-data="auditData" @evaluationSuccess="evaluationSuccess" /> -->

    <!-- 打印立项审批表 -->
    <vue-easy-print
      ref="printApproval"
      table-show
    >
      <!-- 你自己编写打印的模板  -->
      <template slot-scope="func">
        <div id="print-template">
          <approval-print
            :detail-data="detailData"
            :get-chinese-number="func.getChineseNumber"
          />
        </div>
      </template>
    </vue-easy-print>
  </div>
</template>

<script>
import {
  projectInfoDetail,
  projectInfoDetailByFlowId,
  resolutionEvaluate
} from '@/api/projectInformation'
import ItemTitle from '@/components/ItemTitle/index.vue'

export default {
  name: 'ProjectDetail',
  components: {
    BaseInfo: () => import('./modules/baseInfo'),
    MeetingList: () => import('./modules/meetingList.vue'),
    LookInfo: () => import('../../modules/lookInfo.vue'),
    AllLookInfo: () => import('../../modules/allLookInfo.vue'),
    AuditDialog: () => import('../../modules/auditDialog.vue'),
    ApprovalPrint: () => import('../../modules/approvalPrint.vue'),
    ItemTitle
  },
  data() {
    return {
      tabs: '',
      isAllSubmit: false,
      activeName1: '1',
      activeName2: '1',
      projectId: '', // 自研立项id
      flowId: '', // 从公共审核列表过来的id
      detailData: null,
      departmentLookInfo: null,
      departmentList: [], // 参与调查报告的部门，以及是否提交报告
      statusData: {
        info_status: 0
      },
      userInfo: null,
      isJoin: false, // 当前部门是否参与调研
      // 自己所在部门信息
      departmentData: {
        department_id: '',
        department_name: ''
      },
      auditButtonName: '决议审批',
      auditData: {},
      isAudit: false,
      auditForm: {
        check_status: 1
      },
      auditOptions: [
        {
          label: '同意立项',
          value: 1
        },
        {
          label: '不予立项',
          value: 2
        },
        {
          label: '暂时搁置',
          value: 3
        }
      ],
      // 弹框
      rules: {
        check_status: [
          { required: true, message: '请选择评估结论', trigger: 'change' }
        ]
      }
    }
  },
  // 生命周期 - 创建完成（访问当前this实例）
  created() {
    // 是否为提交调研报告
    this.tabs = this.$route.query.tabs
    if (this.tabs && this.tabs === 'subReport') {
      this.activeName1 = '2'
    }
    this.userInfo = this.$store.getters.userInfo
    if (this.userInfo && this.userInfo.user.department) {
      this.departmentData.department_id = this.userInfo.user.department.id
      this.departmentData.department_name =
        this.userInfo.user.department.department_name
    }
    this.projectId = this.$route.query.projectId || ''
    this.flowId = this.$route.query.f_id || ''
    this.fetchData()
    if (this.flowId) {
      this.getAuditData(this.flowId)
    }
  },
  methods: {
    fetchData() {
      this.getDetails().then(() => {
        // this.getLookInfoList({ id: this.projectId })
      })
    },
    lookInfoSuccess() {
      this.getProjectInfoDetail(this.projectId)
      // this.getLookInfoList({ id: this.projectId })
    },
    goBack() {
      this.$router.back()
    },
    printApproval() {
      this.$refs.printApproval.print()
    },
    depTagClick(dep) {
      // 只有自己提交了报告才可看其他部门的
      if (this.isJoin && this.departmentLookInfo) {
        this.departmentData = {
          department_id: dep.department_id,
          department_name: dep.department_name
        }
        const p = this.detailData.department_research.filter(
          (pl) => pl.department_id === this.departmentData.department_id
        )[0]
        this.departmentLookInfo = p || null
      } else {
        this.$message({
          type: 'warning',
          message: '您还没有提交调研报告，不能查看。'
        })
      }
    },

    getAuditData(id) {
      this.$api.PROJECT_START_CHECK_DETAIL(id).then((res) => {
        if (res.code === 200) {
          this.auditData = res.data
          this.getButton()
        }
      })
    },
    getButton() {
      if (
        this.auditData.State !== 'Done' ||
        this.auditData.State !== 'Refuse'
      ) {
        if (this.auditData.Next && this.auditData.Next.length) {
          for (let i = 0; i < this.auditData.Next.length; i++) {
            const data = this.auditData.Next[i]
            const index = data.Staffs.findIndex(
              (a) => a === this.userInfo.user.id
            )
            if (index !== -1) {
              this.isAudit = true
              this.auditButtonName = data.ItemName
              break
            } else {
              this.isAudit = false
            }
          }
        }
      }
    },
    // 获取详情
    getDetails() {
      return new Promise((resove, rej) => {
        const that = this
        let apis = projectInfoDetail
        let ids = ''
        if (this.flowId) {
          apis = projectInfoDetailByFlowId
          ids = this.flowId
        } else {
          apis = projectInfoDetail
          ids = this.projectId
        }
        apis({ id: ids }).then((res) => {
          if (res.code === 200) {
            that.projectId = res.data.id
            that.detailData = res.data
            that.departmentList = res.data.department_research
            // 需求状态
            that.statusData.info_status = that.detailData.info_status
            // 如果是尽调中，判断该部门是否已提交尽调报告
            if (that.statusData.info_status >= 1) {
              const p = that.departmentList.filter(
                (pl) => pl.department_id === that.departmentData.department_id
              )[0]
              that.departmentLookInfo = p || null
            }
            // 判断当前部门是否参与调研
            const p = that.departmentList.filter(
              (pl) => pl.department_id === that.departmentData.department_id
            )
            // 判断是否所有部门都提交了调研报告
            this.isAllSubmit = that.departmentList.every(
              (pl) => pl.if_commit === 1
            )
            if (p.length) {
              that.isJoin = true
            }
            resove()
          }
        })
      })
    },
    // 获取立项详情
    getProjectInfoDetail(id) {
      const that = this
      const datas = { id: id }
      projectInfoDetail(datas).then((res) => {
        if (res.code === 200) {
          that.detailData = res.data
          that.departmentList = res.data.department_research
          // 判断是否为创建人
          if (this.detailData.creator_id === this.userInfo.user?.id) {
            Object.assign(that.detailData, { isCreator: true })
          } else {
            Object.assign(that.detailData, { isCreator: false })
          }
          // 如果是尽调中，判断该部门是否已提交尽调报告
          if (that.statusData.info_status >= 1) {
            const pidx = that.detailData.department_research.findIndex(
              (pl) => pl.department_id === that.departmentData.department_id
            )
            if (pidx !== -1) {
              that.departmentLookInfo =
                that.detailData.department_research[pidx] || null
            }
          }
          // 判断当前部门是否参与调研
          const p = that.departmentList.findIndex(
            (pl) => pl.department_id === that.departmentData.department_id
          )
          // 判断是否所有部门都提交了调研报告
          this.isAllSubmit = that.departmentList.every(
            (pl) => pl.if_commit === 1
          )
          if (p !== -1) {
            that.isJoin = true
            that.depIdx = p
          } else {
            if (that.detailData.isCreator) {
              that.departmentLookInfo = that.detailData.department_research[0]
              that.depIdx = 0
            }
          }
        }
      })
    },
    // 决议审批
    resolutionEvaluateOperation(subdata, callback) {
      resolutionEvaluate(subdata).then((res) => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '审批成功'
          })
          this.$route.params.refresh = true // 返回时刷新列表
          this.getProjectInfoDetail(this.projectId)
          this.getAuditData(this.flowId)
          callback(true)
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    refreshData() {
      this.$route.params.refresh = true // 返回时刷新列表
      this.getProjectInfoDetail(this.projectId)
      this.getAuditData(this.flowId)
    },
    toEdit(affairs) {
      this.$message.warning('暂无此功能')
    },
    // affairsId, stepId , type  //选择类型, template //备注, RejectStepId  //步骤id
    onSubmit(affairsId, stepId, type, template, RejectStepId, callback) {
      console.log(affairsId, stepId, type, template, RejectStepId)
      var that = this
      const subdata = {
        id: this.projectId,
        check_status: type,
        step_id: RejectStepId || '',
        remark: template.Remark,
        Files: template.Files
      }
      if (type === 'Next') {
        subdata.agree_status = this.auditForm.check_status
      }
      console.log(subdata)
      if (type === 'Next') {
        this.$refs['auditForm'].validate((valid) => {
          if (valid) {
            that.resolutionEvaluateOperation(subdata, callback)
          }
        })
      } else {
        that.resolutionEvaluateOperation(subdata, callback)
      }
    },
    onCancel(affairsId, stepId, type, template, RejectStepId, callback) {
      this.$alert('是否确认撤销？', '撤销', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        const subdata = {
          flow_id: this.flowId,
          model_type: 'Resolutions'
        }
        this.$comFun
          .cancelFunc(subdata)
          .then(() => {
            callback(true)
            this.$message({
              type: 'success',
              message: '已撤销'
            })
            this.$route.params.refresh = true // 返回时刷新列表
            this.getProjectInfoDetail(this.projectId)
            this.getAuditData(this.flowId)
          })
          .catch((err) => {
            this.$message.error(err)
          })
      }).catch(err => {
        console.log(err)
      })
    }
    // /** 审批按钮操作 */
    // handleAudit() {
    //   this.$refs.auditDialog.open()
    // },
    // evaluationSuccess() {
    //   this.$route.params.refresh = true // 返回时刷新列表
    //   this.getProjectInfoDetail(this.projectId)
    //   this.getAuditData(this.flowId)
    // }
  }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
@import "@/styles/variables.scss";
.view-container {
  padding-top: 110px;
  .tip-container {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    p {
      margin: 0px;
      padding: 20px 0px;
    }
    .tip-title {
      font-size: $font-size-main;
      color: $font-color-main;
      width: 160px;
      text-align: right;
      padding-right: 12px;
      box-sizing: border-box;
    }
    .department-container {
      .icon {
        margin-left: 4px;
      }
      .el-tag {
        margin-right: 10px;
        &:hover {
          cursor: pointer;
        }
      }
    }
  }
  .status-container {
    margin-bottom: 40px;
  }
}

.tab-content {
  min-height: 200px;
}
</style>
